import { 
	VERSION,
	EXT_NAME,
	GLOB_REG,
	UNIT,
	IMPORTANT,
	OVERRIDE_RULES,
	MEDIA_QUERIES,
	BEFORE_CONTENTS,
	CONFIG_FILE_NAME,
	PREFIX,
	PREFIX_SEPARATOR,
	AUTO_USE_SNIPPETS,
	COLORS,
	CONFIG_FILE,
	ROOT
} from '../constant/index';
import { 
	AUTHOR
} from '../build/constant';
import { AutocssConfig, PluginOptions } from '../types';
import { loadConfig } from 'unconfig'

const fs = require('fs');
const path = require('path');

let pluginOptions: PluginOptions = {
	configFile: ''
}

let programConfig = {
	[OVERRIDE_RULES]: {}
} as any;

const runType = {
	uniapp: {
		[EXT_NAME]: ['vue'],
		reg: /(?:(?<=class=(["']))[\s\S]*?(?=\1))|((?<=class={)[\s\S]*?(?=}))/gi
	}
};

/**
 * 获取配置信息
 */
export const getConfig = (str: string | number): any => {
	switch (str) {
		// 配置默认值
		case EXT_NAME:
			return programConfig[EXT_NAME] || programConfig[programConfig.type] || runType[programConfig.type][EXT_NAME];
		case GLOB_REG:
			return runType[programConfig.type || 'uniapp'].reg;
		case COLORS:
			return programConfig[COLORS] || {};
		case UNIT:
			return programConfig[UNIT] || 'px';
		case MEDIA_QUERIES:
			return programConfig[MEDIA_QUERIES] || {}
		case IMPORTANT:
			return programConfig[IMPORTANT] === undefined ? true : programConfig[IMPORTANT]
		case BEFORE_CONTENTS:
			return programConfig[BEFORE_CONTENTS] || '/* stylelint-disable */'
		case PREFIX:
			return programConfig[PREFIX] || '';
		case PREFIX_SEPARATOR:
			return programConfig[PREFIX] ? (programConfig[PREFIX_SEPARATOR] || '-') : '';
		case AUTO_USE_SNIPPETS:
			return programConfig[AUTO_USE_SNIPPETS] || false;
		default:
			return programConfig[str];

	}
}

/**
 * 加载用户配置
 */
export const loadUserConfig = async () => {
	const configPath = path.resolve(pluginOptions.configFile ?? CONFIG_FILE);
	// const root = process.env.UNI_INPUT_DIR
	// const { config, sources } = await loadConfig({
	// 	sources: [
	// 		{
	// 			files: [`autocss.config`, `auto.config`],
	// 			extensions: ['js', 'mjs']
	// 		}
	// 	],
	// 	merge: false,
	// 	cwd: root
	// });
	// console.log(root);
	// console.log(config);
}

/**
 * 加载插件初始化的配置
 */
export const loadPluginOptions = (options: PluginOptions) => {
	pluginOptions.configFile = options.configFile;
}

/**
 * 设置配置信息
 */
export const setConfig = (config: any): any => {
    programConfig = config;
	return programConfig;
}

/**
 * 获取设置的单位
 * @param number 
 * @param str 
 * @returns 
 */
export const getUnit = (number: string | number, str: string) => {
    if(+number === 0) {
        return '';
    }
    if (str === 'p') {
        return '%';
    }
    if (!str) {
        return programConfig[UNIT] || 'px';
    }
    return str;
}

const getFilePath = (str: any) => {
    return path.resolve(process.env.UNI_INPUT_DIR || process.cwd(), str);
}

export const readConfigFile = (pluginOptions?: PluginOptions) => {
    let options = null;
	const configFile = pluginOptions?.configFile ?? CONFIG_FILE_NAME
    if (fs.existsSync(getFilePath(configFile))) {
        // console.info(`conf path ${getFilePath(CONFIG_FILE_NAME)}`);
        options = require(getFilePath(configFile));
		// 判断全局css文件是否存在
		const cssFilePath = getFilePath((options as any).cssFile)
		if (!fs.existsSync(cssFilePath)) {
			fs.writeFileSync(cssFilePath, '');
		}
        // options = getFilePath(CONFIG_FILE_NAME);
    } else {
        // console.warn(`conf path ${getFilePath(CONFIG_FILE_NAME)}`);
        throw new Error(`请先创建autocss配置文件：${configFile}。`);
    }
    return options;
}
